package com.lekang.system.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Calendar;
import java.util.ArrayList;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.system.domain.SysUserRole;
import com.lekang.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.system.mapper.TaskArrangementMapper;
import com.lekang.system.domain.TaskArrangement;
import com.lekang.system.service.ITaskArrangementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 任务安排Service业务层处理
 *
 * @author zhihao
 * @date 2025-10-14
 */
@Service
public class TaskArrangementServiceImpl implements ITaskArrangementService
{
    private static final Logger log = LoggerFactory.getLogger(TaskArrangementServiceImpl.class);
    
    @Autowired
    private TaskArrangementMapper taskArrangementMapper;


    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    /**
     * 查询任务安排
     *
     * @param id 任务安排主键
     * @return 任务安排
     */
    @Override
    public Map<String, Object> selectTaskArrangementById(Long id)
    {
        return taskArrangementMapper.selectTaskArrangementById(id);
    }

    /**
     * 查询任务安排列表
     *
     * @param taskArrangement 任务安排
     * @return 任务安排
     */
    @Override
    public List<TaskArrangement> selectTaskArrangementList(TaskArrangement taskArrangement)
    {
        return taskArrangementMapper.selectTaskArrangementList(taskArrangement);
    }

    /**
     * 多表联查任务安排列表
     *
     * @param params 查询参数
     * @return 任务安排列表
     */
    @Override
    public List<Map<String, Object>> selectTaskArrangementJoinList(Map<String, Object> params)
    {
        Long userId = SecurityUtils.getUserId();
        System.out.println("========== 任务安排查询 ==========");
        System.out.println("当前用户ID: " + userId);
        
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.getByUserId(userId);
        
        if(sysUserRoles == null || sysUserRoles.isEmpty()){
            System.out.println("用户无角色，查询所有任务");
            return taskArrangementMapper.selectTaskArrangementJoinList(params);
        }
        
        // 打印所有角色信息
        System.out.println("用户角色列表:");
        for(SysUserRole role : sysUserRoles) {
            System.out.println("  - roleId: " + role.getRoleId());
        }
        
        // 检查用户是否有角色ID为100的角色
        boolean hasRole100 = sysUserRoles.stream()
            .anyMatch(role -> role.getRoleId() == 100L);
            
        if(hasRole100){
            // 护理员角色，只能查看分配给自己的任务
            System.out.println("检测到护理员角色(roleId=100)，添加executorId过滤");
            params.put("executorId", userId);
            System.out.println("查询参数: " + params);
            List<Map<String, Object>> result = taskArrangementMapper.selectTaskArrangementJoinList1(params);
            System.out.println("查询结果数量: " + (result != null ? result.size() : 0));
            return result;
        }
        System.out.println("非护理员角色，查询所有任务");
        return taskArrangementMapper.selectTaskArrangementJoinList(params);
    }

    /**
     * 新增任务安排
     *
     * @param taskArrangement 任务安排
     * @return 结果
     */
    @Override
    public int insertTaskArrangement(TaskArrangement taskArrangement)
    {
        taskArrangement.setCreateTime(DateUtils.getNowDate());
        return taskArrangementMapper.insertTaskArrangement(taskArrangement);
    }

    /**
     * 修改任务安排
     *
     * @param taskArrangement 任务安排
     * @return 结果
     */
    @Override
    public int updateTaskArrangement(TaskArrangement taskArrangement)
    {
        return taskArrangementMapper.updateTaskArrangement(taskArrangement);
    }

    /**
     * 批量删除任务安排
     *
     * @param ids 需要删除的任务安排主键
     * @return 结果
     */
    @Override
    public int deleteTaskArrangementByIds(Long[] ids)
    {
        return taskArrangementMapper.deleteTaskArrangementByIds(ids);
    }

    /**
     * 删除任务安排信息
     *
     * @param id 任务安排主键
     * @return 结果
     */
    @Override
    public int deleteTaskArrangementById(Long id)
    {
        return taskArrangementMapper.deleteTaskArrangementById(id);
    }


    @Override
    public Map<String, Object> selectTaskArrangementDetail(Long id) {
        return taskArrangementMapper.selectTaskArrangementDetail(id);
    }

    @Override
    public List<Map<String, Object>> selectTaskArrangementByStatus(Map<String, Object> params) {
        return taskArrangementMapper.selectTaskArrangementByStatus(params);
    }

    @Override
    public List<Map<String, Object>> selectPcTodayPending(Map<String, Object> params) {
        Long userId = SecurityUtils.getUserId();
        System.out.println("========== 今日待执行查询 ==========");
        System.out.println("当前用户ID: " + userId);
        
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.getByUserId(userId);
        
        if(sysUserRoles != null && !sysUserRoles.isEmpty()){
            // 打印所有角色信息
            System.out.println("用户角色列表:");
            for(SysUserRole role : sysUserRoles) {
                System.out.println("  - roleId: " + role.getRoleId());
            }
            
            // 检查用户是否有角色ID为100的角色
            boolean hasRole100 = sysUserRoles.stream()
                .anyMatch(role -> role.getRoleId() == 100L);
                
            if(hasRole100){
                // 护理员角色，只能查看分配给自己的今日待执行任务
                System.out.println("检测到护理员角色(roleId=100)，添加executorId过滤");
                params.put("executorId", userId);
                System.out.println("今日待执行查询参数: " + params);
            } else {
                System.out.println("非护理员角色，查询所有今日待执行任务");
            }
        }
        
        List<Map<String, Object>> result = taskArrangementMapper.selectPcTodayPending(params);
        System.out.println("今日待执行查询结果数量: " + (result != null ? result.size() : 0));
        return result;
    }

    @Override
    public int cancelTask(Map<String, Object> params) {
        return taskArrangementMapper.cancelTask(params);
    }

    @Override
    public int executeTask(Map<String, Object> params) {
        return taskArrangementMapper.executeTask(params);
    }

    @Override
    public int rescheduleTask(Map<String, Object> params) {
        return taskArrangementMapper.rescheduleTask(params);
    }

    @Override
    public List<Map<String, Object>> selectNursingProjectsForSearch(Map<String, Object> params) {
        return taskArrangementMapper.selectNursingProjectsForSearch(params);
    }

    @Override
    public int generateNursingPlanTasks(Map<String, Object> params) {
        return taskArrangementMapper.generateNursingPlanTasks(params);
    }

    @Override
    public int generateNonNursingPlanTasks(Map<String, Object> params) {
        return taskArrangementMapper.generateNonNursingPlanTasks(params);
    }

    @Override
    public int generateTasksByCycle(Long elderlyId, Long nursingItemId, String executionCycleType, 
                                   Integer executionFrequency, Date plannedStartTime, String projectType) {
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("elderlyId", elderlyId);
        params.put("nursingItemId", nursingItemId);
        params.put("executionCycleType", executionCycleType);
        params.put("executionFrequency", executionFrequency);
        params.put("plannedStartTime", plannedStartTime);
        params.put("projectType", projectType);
        
        return taskArrangementMapper.generateTasksByCycle(params);
    }

    /**
     * 生成每日任务
     */
    public int generateDailyTasks(Long elderlyId, Long nursingItemId, Integer executionFrequency, 
                                 Date plannedStartTime, String projectType) {
        List<TaskArrangement> tasks = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(plannedStartTime);
        
        // 计算时间间隔：(24 - 开始时间) / 执行频次
        int startHour = cal.get(Calendar.HOUR_OF_DAY);
        int interval = (24 - startHour) / executionFrequency;
        
        for (int i = 0; i < executionFrequency; i++) {
            TaskArrangement task = new TaskArrangement();
            task.setElderlyId(elderlyId);
            task.setProjectNameId(nursingItemId);
            task.setProjectType(projectType);
            task.setStatus("待执行");
            task.setCreateTime(DateUtils.getNowDate());
            
            // 计算期望服务时间
            Calendar taskCal = Calendar.getInstance();
            taskCal.setTime(plannedStartTime);
            taskCal.add(Calendar.HOUR_OF_DAY, i * interval);
            task.setExpectedServiceTime(taskCal.getTime());
            
            tasks.add(task);
        }
        
        // 批量插入任务
        int result = 0;
        for (TaskArrangement task : tasks) {
            result += taskArrangementMapper.insertTaskArrangement(task);
        }
        return result;
    }

    /**
     * 生成每周任务
     */
    public int generateWeeklyTasks(Long elderlyId, Long nursingItemId, Integer executionFrequency, 
                                  Date plannedStartTime, String projectType) {
        List<TaskArrangement> tasks = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(plannedStartTime);
        
        // 计算日期间隔：7天 / 执行频次
        int dayInterval = 7 / executionFrequency;
        
        for (int i = 0; i < executionFrequency; i++) {
            TaskArrangement task = new TaskArrangement();
            task.setElderlyId(elderlyId);
            task.setProjectNameId(nursingItemId);
            task.setProjectType(projectType);
            task.setStatus("待执行");
            task.setCreateTime(DateUtils.getNowDate());
            
            // 计算期望服务时间
            Calendar taskCal = Calendar.getInstance();
            taskCal.setTime(plannedStartTime);
            taskCal.add(Calendar.DAY_OF_MONTH, i * dayInterval);
            task.setExpectedServiceTime(taskCal.getTime());
            
            tasks.add(task);
        }
        
        // 批量插入任务
        int result = 0;
        for (TaskArrangement task : tasks) {
            result += taskArrangementMapper.insertTaskArrangement(task);
        }
        return result;
    }

    /**
     * 生成每月任务
     */
    public int generateMonthlyTasks(Long elderlyId, Long nursingItemId, Integer executionFrequency, 
                                   Date plannedStartTime, String projectType) {
        List<TaskArrangement> tasks = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(plannedStartTime);
        
        // 计算日期间隔：30天 / 执行频次
        int dayInterval = 30 / executionFrequency;
        
        for (int i = 0; i < executionFrequency; i++) {
            TaskArrangement task = new TaskArrangement();
            task.setElderlyId(elderlyId);
            task.setProjectNameId(nursingItemId);
            task.setProjectType(projectType);
            task.setStatus("待执行");
            task.setCreateTime(DateUtils.getNowDate());
            
            // 计算期望服务时间
            Calendar taskCal = Calendar.getInstance();
            taskCal.setTime(plannedStartTime);
            taskCal.add(Calendar.DAY_OF_MONTH, i * dayInterval);
            task.setExpectedServiceTime(taskCal.getTime());
            
            tasks.add(task);
        }
        
        // 批量插入任务
        int result = 0;
        for (TaskArrangement task : tasks) {
            result += taskArrangementMapper.insertTaskArrangement(task);
        }
        return result;
    }

    /**
     * 刷新未执行任务，隐藏已退住老人的任务
     */
    @Override
    public void refreshUnexecutedTasks() {
        // 这里可以实现刷新逻辑，比如更新任务状态或隐藏已退住老人的任务
        // 具体实现可以根据业务需求来定义
        log.info("刷新未执行任务完成");
    }

    /**
     * 生成当月护理计划内任务
     */
    @Override
    public void generateMonthlyInPlanTasks(java.time.LocalDate monthStart, java.time.LocalDate monthEnd) {
        // 查询所有有效的护理合同
        // 根据合同信息生成当月所有护理计划内任务
        log.info("生成当月护理计划内任务: {} 到 {}", monthStart, monthEnd);
    }

    /**
     * 生成入住首月护理计划内任务
     */
    @Override
    public void generateFirstMonthInPlanTasks(Long elderlyId, java.time.LocalDate checkInDate, java.time.LocalDate firstMonthEnd) {
        // 根据老人ID查询护理合同
        // 生成首月护理计划内任务
        log.info("生成入住首月护理任务: 老人ID={}, 入住日期={}, 首月结束={}", elderlyId, checkInDate, firstMonthEnd);
    }

    /**
     * 生成护理计划外任务
     */
    @Override
    public void generateOutOfPlanTask(Long elderlyId, Long nursingItemId, java.time.LocalDateTime serviceTime, String orderNo) {
        TaskArrangement task = new TaskArrangement();
        task.setElderlyId(elderlyId);
        task.setProjectNameId(nursingItemId);
        task.setProjectType("护理计划外");
        task.setExpectedServiceTime(java.sql.Timestamp.valueOf(serviceTime));
        task.setStatus("待执行");
        task.setRelatedOrderNo(orderNo);
        task.setCreateTime(new java.util.Date());
        
        taskArrangementMapper.insertTaskArrangement(task);
        log.info("生成护理计划外任务: 老人ID={}, 护理项目ID={}, 服务时间={}", elderlyId, nursingItemId, serviceTime);
    }
}